<?php

class Grid_Core
{
	protected $fields;
	protected $action_fields;
	protected $add_button = FALSE;
	protected $base_uri;
	protected $template = 'grid_template';
	protected $title;

	public function __construct($base_uri, $title, $template = FALSE)
	{

		if ($template) {
			$this->template = $template;
		}
		$this->template = new View($this->template);
		$this->template->base_uri = $this->base_uri = $base_uri;
		$this->template->title = $title;
	}

	public function __set($key, $value)
	{
		$this->$key = $value;
	}

	public function add_new_button($uri, $label, $absolute_uri = FALSE)
	{
		if ($absolute_uri == FALSE) {
			$this->template->add_button = html::anchor($this->base_uri.$uri, $label);
		} else {
			$this->template->add_button = html::anchor($uri, $label);
		}

	}
	/**
	 * Magic __call method. Creates a new form element object.
	 *
	 * @throws  Kohana_Exception
	 * @param   string   input type
	 * @param   string   input name
	 * @return  object
	 */
	public function __call($method, $args)
	{
		// Class name
		$field = ucfirst($method);

		// Create the input
		$field = new $field($args[0]);

		if ( ! ($field instanceof Field)) {
			throw new Kohana_Exception('grige.unknown_field', get_class($field));
		}

		$this->fields[] = $field;
		return $field;
	}

	public function datasource($items)
	{
		$this->template->items = $items;
	}

	public function render()
	{
		$this->template->fields = $this->fields;
		$this->template->action_fields = $this->action_fields;

		return $this->template->render();
	}

	public function __toString()
	{
		return $this->render();
	}
}
